package com.atguigu.test1;

import java.util.concurrent.*;

public class SellTicketByThreadPool {
    //资源类
    static class sellTicket{
        private int ticket  = 500;
        //操作
        public synchronized void sell(){
            if (ticket > 0) {
                ticket--;
                System.out.println(Thread.currentThread().getName() + "卖出了第" + (500 - ticket) + "张票，剩余" + ticket + "张票");
            } else {
                System.out.println("票卖完了");
            }
        }
    }
    public static void main(String[] args) {
        //创建线程池
        ExecutorService executorService = new ThreadPoolExecutor(
                3, 5, 2,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(10),
                Executors.defaultThreadFactory(),
                (r, executor) -> {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
        );
        sellTicket sellTicket = new sellTicket();
        for (int i = 0; i < 3; i++) {
            executorService.submit(()->{
                for (int j = 0; j < 500; j++) {
                    sellTicket.sell();
                }
            });
        }
    }
}
